package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.Instructor;
import com.sky.mapper.InstructorMapeer;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private InstructorMapeer instructorMapeer;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
       try {
           String token = request.getHeader(jwtProperties.getAdminTokenName());
           String startupId = (String) redisTemplate.opsForValue().get("jwt:startup-id");
           Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
           String UserId = claims.get(JwtClaimsConstant.USER_ID).toString();
           String key = "jwt:whitelist:" + startupId + UserId;
           // 验证token
           if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
               response.setStatus(401);
               return false;
           } else {
               log.info("用户ID: {}，token验证通过", UserId);
               BaseContext.setCurrentId(UserId);
               return true;
           }
       }catch (Exception e) {
           log.error("JWT令牌校验失败: {}", e.getMessage());
           response.setStatus(401);
           return false;
       }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        BaseContext.removeCurrentId(); // 清理，防止线程污染
    }
}
